package cn.y.operation.framework.exception;

import cn.y.operation.framework.enums.ResponseMsgEnum;
import cn.y.operation.framework.mvc.ResponseMsg;
import cn.y.operation.framework.utils.system.ServletUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 全局异常处理类--ajax
 * @author 烨
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseMsg handleException(Exception e) {
        logger.error(e.getMessage(), e);
        return new ResponseMsg(ResponseMsgEnum.EXCEPTION_ERR);
    }

    /**
     * 拦截未授权页面
     */
    @ResponseStatus(value = HttpStatus.FORBIDDEN)
    @ExceptionHandler({UnauthorizedException.class, AuthorizationException.class})
    public Object handleAuthorizationException(HttpServletRequest request, UnauthorizedException e) {
        logger.error(e.getMessage(), e);
        if (ServletUtils.isAjaxRequest(request)) {
            return ResponseMsg.error(ResponseMsgEnum.NO_PERMISSION);
        } else {
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("error/unauth");
            return modelAndView;
        }
    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public ResponseMsg handleException(HttpRequestMethodNotSupportedException e) {
        logger.error(e.getMessage(), e);
        return ResponseMsg.error("不支持' " + e.getMethod() + "'请求");
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseMsg notFount(RuntimeException e) {
        logger.error("运行时异常:", e);
        return ResponseMsg.error("运行时异常:" + e.getMessage());
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseMsg validatedBindException(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        StringBuilder message = new StringBuilder();
        if (result.hasErrors()) {
            List<ObjectError> errors = result.getAllErrors();
            errors.forEach(p -> {
                FieldError fieldError = (FieldError) p;
                logger.error("错误的请求参数: ,dto entity [" + fieldError.getObjectName() + "]" +
                        " ,field [" + fieldError.getField() + "] ,message [" + fieldError.getDefaultMessage() + "]");
                message.append(fieldError.getDefaultMessage());
            });
        }
        return ResponseMsg.error(message.toString());
    }

    /**
     * 处理@Validated参数校验失败异常
     *
     * @param e 异常类
     * @return 响应
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseMsg businessException(BindException e) {
        StringBuilder message = new StringBuilder();
        List<ObjectError> errors = e.getAllErrors();
        errors.forEach(p -> {
            FieldError fieldError = (FieldError) p;
            logger.error("错误的请求参数: ,类 [" + fieldError.getObjectName() + "]" +
                    " ,字段 [" + fieldError.getField() + "] ,信息 [" + fieldError.getDefaultMessage() + "]");
            message.append(fieldError.getDefaultMessage());
        });
        return ResponseMsg.error(message.toString());
    }
}
